package com.toilet.easyvideofx.controller;

import com.toilet.easyvideofx.domain.Sysconfig;
import com.toilet.easyvideofx.global.GlobalCache;
import com.toilet.easyvideofx.constant.SystemConstant;
import com.toilet.easyvideofx.manager.LoginManager;
import com.toilet.easyvideofx.service.SysConfigService;
import com.toilet.easyvideofx.service.impl.SysConfigServiceImpl;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * 登录controller
 */
public class LoginController implements Initializable {
//    private final Login loginHande = new Login();
    /**
     * 登录界面主容器
     */
    public VBox content;
    /**
     * 账号
     */
    public TextField account;
    /**
     * 密码
     */
    public PasswordField password;

    /**
     * 注册按钮
     */
    public Button register;
    /**
     * 登录按钮
     */
    public Button login;

    private final LoginManager loginManager = new LoginManager();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        SysConfigService sysConfigService = new SysConfigServiceImpl();
        Sysconfig accountAndPwd = sysConfigService.selectByTag("账号");
        if (accountAndPwd != null) {
            account.setText(accountAndPwd.getValue());
            password.setText(accountAndPwd.getKey());
        }
    }

    /**
     * 登录按钮事件
     *
     * @param actionEvent
     */
    public void login(ActionEvent actionEvent) throws IOException {
        if (account.getText().isEmpty() || password.getText().isEmpty()) {
            return;
        }
        Boolean result = loginManager.login(account.getText(), password.getText());
        if (result) {
            Stage stage = GlobalCache.get(SystemConstant.MAIN_STAGE, Stage.class);
            stage.setTitle("主界面");
            stage.setWidth(800);
            stage.setHeight(600);
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main-view.fxml"));
            Scene mainScene = new Scene(fxmlLoader.load());
            //允许改变窗口大小
            stage.setResizable(true);
            stage.setScene(mainScene);
        }
    }

    public void register(ActionEvent actionEvent) throws IOException {
        Stage stage = GlobalCache.get(SystemConstant.MAIN_STAGE, Stage.class);
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/register-view.fxml"));
        Scene registerScene = new Scene(fxmlLoader.load());
        stage.setTitle("注册");
        //登录界面设定无法改变大小
        stage.setResizable(false);
        stage.setScene(registerScene);
    }
}
